<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/7/13 20:09
 */

namespace App\Project\Traits\Validator;

use App\Models\MedicalRecord;
use App\Models\Patient;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Validation\Validator;

trait GreaterThanBirthday
{
    protected $messages = '日期 不能早于出生日期';

    /**
     * @param \Illuminate\Validation\Validator $validator
     * @param array                            $fields
     * @param array                            $messages
     */
    public function ifGreaterThanBirthday(Validator $validator, array $fields, $messages = [])
    {
        $birthday = $this->getPatientBirthday();

        collect($fields)->filter(function ($field) use ($birthday) {

            $value = $this->input($field);

            if (empty($value) && strtotime($value) > 0) {
                return Carbon::parse($value)->gt($birthday);
            }

            return false;
        })->map(function ($value) use ($validator, $messages) {

            $tip = Arr::has($messages, $value) ? Arr::get($messages, $value) : $this->messages;

            $validator->errors()->add($value, $tip);
        });
    }

    /**
     * @return \Carbon\Carbon
     */
    protected function getPatientBirthday()
    {
        $birthday = null;

        if ($patient_id = $this->input('patient_id')) {
            $birthday = (new Patient())->getWithCache($patient_id)->birthday;
        } elseif ($record_id = $this->input('record_id')) {

            $patient_id = (new MedicalRecord())->getWithCache($record_id)->patient_id;
            $birthday   = (new Patient())->getWithCache($patient_id)->birthday;
        }

        return ($birthday instanceof Carbon) ? $birthday : Carbon::parse($birthday);
    }
}